<?php

namespace app\wechat\controller;

use app\common\model\Users;
use app\wechat\lib\Wechat;
use EasyWeChat\Factory;
use think\App;
use think\Controller;
use think\Db;

class Oauth extends Controller
{
    protected $app = null;
    //支付成功发送模板消息
    public function login()
    {
        $redirect_uri = url('wechat/oauth/callback');
        $config       = [
            // 前面的appid什么的也得保留哦
            'app_id'        => Wechat::app_id,
            'mch_id'        => Wechat::mch_id,
            'secret'        => Wechat::secret,
            'response_type' => 'array',
            'key'           => Wechat::key,
            'notify_url'    => $redirect_uri,     // 你也可以在下单时单独设置来想覆盖它

            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => $redirect_uri,
            ],
        ];

        $app   = Factory::officialAccount($config);
        $oauth = $app->oauth;
        if (!session('?user')) {
            return $oauth->redirect()->send();
        }

    }


    public function callback()
    {
        $config = [
            // 前面的appid什么的也得保留哦
            'app_id'        => Wechat::app_id,
            'mch_id'        => Wechat::mch_id,
            'secret'        => Wechat::secret,
            'response_type' => 'array',
            'key'           => Wechat::key,
            'oauth'         => [
                'scopes' => ['snsapi_userinfo'],
            ],
        ];
        $app    = Factory::officialAccount($config);
        $oauth  = $app->oauth;
        $user   = $oauth->user();
        $isUser = Db::table('wyc_users')->where('openid', $user['id'])->find();
        if ($isUser) {
            $isUser = model('Users')->where('openid', $user['id'])->find();
        }
        if (!$isUser) {
            $new_user = Users::create($user['original']);
            $session  = [
                'id'         => $new_user->id,
                'nickname'   => $user['name'],
                'openid'     => $user['id'],
                'headimgurl' => $user['avatar'],
            ];
            session('user', $session);
        } else {
            $session = [
                'id'         => $isUser->id,
                'nickname'   => $isUser->nickname,
                'openid'     => $isUser->openid,
                'headimgurl' => $isUser->headimgurl,
            ];
            session('user', $session);
        }
        $url = session('url');
        if (!$url) {
            $url = url('wechat/personal/index');
        }
        header('location:' . $url);
    }


}



